import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';

const int defaultPageSize = 20;

abstract mixin class BaseListMixin<M> {
  EasyRefreshController refreshController = EasyRefreshController(
    controlFinishLoad: true,
      controlFinishRefresh: true
  );

  // 存储分页数据的列表
  List<M> dataList = [];
  int _pageIndex = 1;
  final int _pageSize = defaultPageSize;

  // 回调用于通知 UI 数据更新
  void onListDataChanged();

  Future onRefresh() async {
    await loadData(loadMore: false);
  }

  Future onLoad() async {
    await loadData(loadMore: true);
  }

  Future<void> loadData({bool loadMore = false}) async {
    /// 刷新
    if (!loadMore) _pageIndex = 1;

    try {
      List<M> res = await getData(_pageIndex, _pageSize);
      if (loadMore) {
        if (res.isNotEmpty) {
          /// 加载更多

          int lastPageSize = dataList.length ~/ _pageSize;
          /// 数量不变，无新增
          if (lastPageSize == res.length) {
            // refreshController.loadNoData();
            refreshController.finishLoad(IndicatorResult.noMore);
            return;
          } else {
            /// 去掉最后一页旧数据
            dataList = (List.of(dataList))
              ..removeRange(lastPageSize * _pageSize, dataList.length)
              ..addAll(res);
          }

          if (res.length == _pageSize) _pageIndex++;
          // refreshController.loadComplete();
          refreshController.finishLoad(IndicatorResult.success);

        } else {
          // refreshController.loadNoData();
          refreshController.finishLoad(IndicatorResult.noMore);
        }
        onListDataChanged();
      } else {
        /// 刷新
        dataList = [];
        dataList = res;
        // refreshController.refreshCompleted();
        refreshController.finishRefresh();
        onListDataChanged();
      }
    } catch (e) {
      debugPrint('base list mixin error: ${e.toString()}');
      if (loadMore) {
        // refreshController.loadFailed();
        refreshController.finishLoad(IndicatorResult.fail);
      } else {
        // refreshController.refreshFailed();
        refreshController.finishRefresh(IndicatorResult.fail);
      }
    }
  }

  /// request data
  Future<List<M>> getData(pageIndex, pageSize);

}
